package com.algorithm.commonsort;

/**
 * Created with IntelliJ IDEA.
 * User: LK
 * Date: 2018/4/2
 * Time: 18:41
 * To change this template use File | Settings | File Templates.
 * Description: 冒泡排序
 */
public class BubbleSort {

    /**
     *  冒泡排序方法1
     * @param inputArray
     * @return
     */
    public static int[] bubbleSort(int[] inputArray){

        int length = inputArray.length;
        for (int i = 0; i < length - 1; i++) {
            for (int j = 0; j < length - 1 - i; j++) {
                if (inputArray[j] > inputArray[j + 1]) {
                    int temp = inputArray[j];
                    inputArray[j] = inputArray[j + 1];
                    inputArray[j+1] = temp;
                }
            }
        }
        return inputArray;
    }

    public static void main(String[] args) {

        int[] ints = {2,1,3,5,4,7,6,8,9,5};
        print(ints);
        int[] bubbleSort = bubbleSort(ints);
        print(bubbleSort);

    }

    /**
     *  打印数组
     * @param printArray
     */
    public static void print(int[] printArray){
        if (printArray != null && printArray.length > 0) {
            for (int i = 0; i < printArray.length; i++) {
                if (i == 0) {
                    System.out.print("[");
                }
                System.out.print(printArray[i]+" ");
                if (i == printArray.length - 1) {
                    System.out.println("]");
                }
            }
        }else
            System.out.println("要打印的数组不能为空！");
    }

    /**
     *  冒泡排序2
     * @param arr
     * @return
     */
    public static int[] sort(int[] arr) {
        int temp;
        for (int i = 0; i < arr.length; i++) {
            for (int j = arr.length - 1; j>i ; j--) {
                if (arr[j] < arr[j - 1]) {
                    temp = arr[j];
                    arr[j] = arr[j - 1];
                    arr[j - 1] = temp;
                }
            }
        }
        return arr;
    }

}
